package cn.ito.zjgsu.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import cn.ito.zjgsu.constant.StatusCode;
import cn.ito.zjgsu.domain.Role;
import cn.ito.zjgsu.domain.RoleExample;
import cn.ito.zjgsu.domain.UserLogin;
import cn.ito.zjgsu.domain.UserLoginExample;
import cn.ito.zjgsu.mapping.RoleAuthorityMapper;
import cn.ito.zjgsu.mapping.RoleMapper;
import cn.ito.zjgsu.mapping.UserLoginMapper;
import cn.ito.zjgsu.service.RolePermissionService;
import cn.ito.zjgsu.service.UserService;
import cn.ito.zjgsu.utils.EncryptGenerator;
import cn.ito.zjgsu.utils.ExcelReader;
import cn.ito.zjgsu.utils.PrimaryKeyGenerator;
import cn.ito.zjgsu.utils.RandomStringUtil;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Resource
	private UserLoginMapper userLoginMapper;

	@Resource
	private RoleMapper roleMapper;

	@Resource
	private RoleAuthorityMapper roleAuthorityMapper;

	@Resource
	private PrimaryKeyGenerator primaryKeyGenerator;

	@Resource
	private RandomStringUtil randomStringUtil;

	@Resource
	private EncryptGenerator encryptGenerator;

	@Resource
	private ExcelReader excelReader;

	@Resource
	private RolePermissionService rolePermissionService;
	
	
	

	@Override
	public String insertUser(UserLogin user) {

		String status;

		try {
			user.setSalt(randomStringUtil.getRandomString());
			user.setPassword(encryptGenerator.encrypt(user.getPassword(), user.getSalt()));
			user.setLoginDeleteTags(UserLogin.USER_EXISTS_FLAG);
			userLoginMapper.insertSelective(user);
			status = StatusCode.SUCCESS_STATUS;

		} catch (Exception e) {
			e.printStackTrace();
			status = StatusCode.FAILURE_STATUS;

		}
		Map<String, String> json = new HashMap<String, String>();
		json.put(StatusCode.STATUS, status);
		return JSON.toJSONString(json);

	}

	public UserLogin findUserByUsername(String username) {
		UserLoginExample userExample = new UserLoginExample();
		userExample.or().andUsernameEqualTo(username).andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG);
		if (userLoginMapper.selectByExample(userExample).size() == 0) {
			return null;
		} else {
			return userLoginMapper.selectByExample(userExample).get(0);
		}
	}

	public String addRole4User(Role role, UserLogin user) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			UserLogin record = new UserLogin();
			record.setRoleId(role.getRoleId());
			UserLoginExample userLoginExample = new UserLoginExample();
			userLoginExample.or().andLoginIdEqualTo(user.getLoginId())
					.andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG);
			userLoginMapper.updateByExampleSelective(user, userLoginExample);
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			status = StatusCode.FAILURE_STATUS;
			e.printStackTrace();
		}
		return status;
	}

	public List<UserLogin> findUserByRole(Role role) {
		UserLoginExample userLoginExample = new UserLoginExample();
		int rid = getRid(role);
		userLoginExample.or().andRoleIdEqualTo(rid).andLoginDeleteTagsEqualTo(Role.ROLE_EXISTS_FLAG);
		return userLoginMapper.selectByExample(userLoginExample);
	}

	private int getRid(Role role) {

		int rid = 0;
		if (role.getRoleId() != Role.EMPTY_ID) {
			rid = role.getRoleId();
		} else if (role.getRoleName() != Role.EMPTY_NAME) {
			RoleExample roleExample = new RoleExample();
			roleExample.or().andRoleNameEqualTo(role.getRoleName()).andRoleDeleteTagsEqualTo(Role.ROLE_EXISTS_FLAG);
			rid = (roleMapper.selectByExample(roleExample)).get(0).getRoleId();

		}
		return rid;
	}

	@Override
	public String addUser2Role(UserLogin user, int rid) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			user.setRoleId(rid);
			userLoginMapper.insertSelective(user);
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			status = StatusCode.FAILURE_STATUS;
			e.printStackTrace();
		}
		return status;

	}

	@Override
	public List<UserLogin> queryUserByRole(int rid) {
		
		UserLoginExample userLoginExample = new UserLoginExample();
		userLoginExample.or().andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG)
		.andRoleIdEqualTo(rid);
		List<UserLogin> users = userLoginMapper.selectByExample(userLoginExample);
		return users;
	}

	@Override
	public UserLogin queryUserById(int uid) {
		UserLoginExample userLoginExample = new UserLoginExample();
		userLoginExample.or().andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG)
		.andLoginIdEqualTo(uid);
		return userLoginMapper.selectByExample(userLoginExample).get(0);
	}
	
	@Override
	public List<UserLogin> queryUsersByIds(List<Integer> uids) {
		UserLoginExample userLoginExample = new UserLoginExample();
		userLoginExample.or().andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG)
		.andLoginIdIn(uids);
		return userLoginMapper.selectByExample(userLoginExample);
	}
	
	
	@Override
	public String linkUser(int uid, int rid) {
		String status = StatusCode.FAILURE_STATUS;
		try{
			UserLogin user = queryUserById(uid);
			addUser2Role(user,rid);
			status = StatusCode.SUCCESS_STATUS;
		}catch(Exception e){
			status = StatusCode.FAILURE_STATUS;
		}
		return status;
	}

	@Override
	public List<Integer> queryAllaccountIds() {
		UserLoginExample userLoginExample = new UserLoginExample();
		userLoginExample.or().andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG);
		List<UserLogin> users = userLoginMapper.selectByExample(userLoginExample);
		List<Integer> aids = new ArrayList<Integer>();
		for(UserLogin u : users){
			aids.add(u.getLoginId());
		}	
		return aids;
	}

	@Override
	public List<Integer> getSelectedAccountIds(Integer[] accountIds, Integer[] cancelIds) {
		List<Integer> aids = new ArrayList<Integer>();
		if(null == accountIds){		
			aids.addAll(queryAllaccountIds());
			aids.retainAll(Arrays.asList(cancelIds));
		}else if(null == cancelIds){
			aids.addAll(Arrays.asList(accountIds));
		}
		return aids;
	}

	@Override
	public String linkUsers(List<Integer> uids, int roleId) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			List<UserLogin> users = queryUsersByIds(uids);
			for(UserLogin user : users){
				user.setRoleId(roleId);
			}
			userLoginMapper.insertList(users);
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			status = StatusCode.FAILURE_STATUS;
		}
		return status;
	}

	@Override
	public String dislinkUsers(List<Integer> uids, int roleId) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			UserLogin user = new UserLogin();
			user.setRoleId(Role.NO_ROLE_ID);
			UserLoginExample userLoginExample = new UserLoginExample();
			userLoginExample.or().andLoginDeleteTagsEqualTo(Role.ROLE_DELETE_FLAG)
			.andLoginIdIn(uids);
			userLoginMapper.updateByExample(user, userLoginExample);
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			status = StatusCode.FAILURE_STATUS;
		}
		return status;
	}

	public String getUserName(UserLogin user){
		return (user.getRoleId()!=null? user.getRoleId():"0") + randomStringUtil.getRandomString();
	}
	
	@Override
	public boolean generateUser(UserLogin user) {
		try{
			user.setUsername(getUserName(user));
			user.setSalt(randomStringUtil.getRandomString());
			user.setPassword(encryptGenerator.encrypt("123456", user.getSalt()));
			user.setLoginDeleteTags(UserLogin.USER_EXISTS_FLAG);
			return true;
		}catch(Exception e){
			return false;
		}
		
	}

	@Override
	public int insertUsers(List<UserLogin> users) {
		if(null != users && !users.isEmpty()){
			return userLoginMapper.insertList(users);
		}else{
			return 0;
		}
		
		
	}

	@Override
	public void deleteUsers(List<UserLogin> users) {
		UserLogin user = new UserLogin();
		user.setLoginDeleteTags(false);
		UserLoginExample userLoginExample = new UserLoginExample();
		List<Integer> uids = new ArrayList<Integer>();
		for(UserLogin u : users){
			uids.add(u.getLoginId());
		}
		if(!uids.isEmpty()){
			userLoginExample.or().andLoginIdIn(uids);	
		}	
		userLoginMapper.updateByExampleSelective(user, userLoginExample);
	}

	@Override
	public List<UserLogin> queryUsersBypidsandRoleId(List<Integer> pids, int roleId) {
		UserLoginExample userLoginExample = new UserLoginExample();
		if(null != pids && !pids.isEmpty()){
			userLoginExample.or().andPersonIdIn(pids).andRoleIdEqualTo(roleId).andLoginDeleteTagsEqualTo(UserLogin.USER_EXISTS_FLAG);
			return userLoginMapper.selectByExample(userLoginExample);
		}else{
			return new ArrayList<UserLogin>();
		}
		
		
		
	}

	



	
	

	

	
	

	

	
	

}
